#!/bin/bash

# 设置默认项目名称并允许用户自定义
#${parameter:-default}
PROJECT_NAME=${1:-project}

# 检查并创建主项目文件夹
# 创建成功返回0 屏蔽或||之后的语句 ， {}用于将多条语句组合，用分号分隔， exit 1 退出返回1表示出错
if [ ! -d "$PROJECT_NAME" ]; then
    mkdir -p "$PROJECT_NAME" || { echo "Failed to create project directory"; exit 1; }
else
    echo "Project folder already exists."
    exit 0
fi

# 使用绝对路径避免频繁切换目录带来的问题
BASE_DIR=$(pwd)/"$PROJECT_NAME"

# 创建子目录
for dir in data/raw data/processed data/interim notebooks src logs tests submissions; do
    mkdir -p "$BASE_DIR/$dir" || { echo "Failed to create directory: $dir"; exit 1; }
done

# 创建子目录和必要文件的函数
# mkdir -p 表示不存在时创建 存在时不修改
create_file_with_parents() {
    local file_path="$1"
    local dir_path=$(dirname "$file_path")
    
    # 确保父目录存在
    mkdir -p "$dir_path" || { echo "Failed to create directory: $dir_path"; exit 1; }
    
    # 创建文件
    touch "$file_path" || { echo "Failed to create file: $file_path"; exit 1; }
}


# 创建必要文件
create_file_with_parents "$BASE_DIR/notebooks/exploration.ipynb"
create_file_with_parents "$BASE_DIR/notebooks/preprocessing.ipynb"
create_file_with_parents "$BASE_DIR/notebooks/modeling.ipynb"
create_file_with_parents "$BASE_DIR/src/data/preprocess.py"
create_file_with_parents "$BASE_DIR/src/features/build_features.py"
create_file_with_parents "$BASE_DIR/src/models/train_model.py"
create_file_with_parents "$BASE_DIR/src/utils/helper.py"
create_file_with_parents "$BASE_DIR/submissions/submission.csv"
create_file_with_parents "$BASE_DIR/requirements.txt"
create_file_with_parents "$BASE_DIR/.gitignore"

# 获取 BASE_DIR 的父目录路径
#  %/* 表示从右边开始删除第一个匹配 / 及其右边的所有字符，从而保留左边的部分，即父目录路径
PARENT_DIR="${BASE_DIR%/*}"
cp "$PARENT_DIR/project_structure" "$BASE_DIR/README.md" || { echo "cp project_structure to readme failed"; exit 1;}

echo "Project structure created successfully."
